package com.lab.utils;

import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.text.TextUtils;

/**
 * Created by ak
 */
public class ThreadUtil {
    public static final Handler MAIN_THREAD_HANDLER = new Handler(Looper.getMainLooper());
    private static String processName = "";

    /**
     * 判断当前线程是否为主线程
     *
     * @return
     */
    public static boolean isUIThread() {
        Looper mLooper = Looper.myLooper();
        if (mLooper != null && mLooper == Looper.getMainLooper()) {
            return true;
        }
        return false;
    }

    public static void throwIfUIThread() {
        if (isUIThread()) {
            throw new RuntimeException("u can not do this action in UI Thread!");
        }
    }

    public static String getCurProcessName(Context context) {
        if (!TextUtils.isEmpty(processName)) {
            return processName;
        }
        int pid = android.os.Process.myPid();
        android.app.ActivityManager mActivityManager = (android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (android.app.ActivityManager.RunningAppProcessInfo appProcess : mActivityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                processName = appProcess.processName;
                return processName;
            }
        }
        return "";
    }

    public static boolean isInUIProcess(Context context) {
        if (!TextUtils.isEmpty(processName)) {
            return processName.equals(context.getApplicationContext().getPackageName());
        }
        int pid = android.os.Process.myPid();
        android.app.ActivityManager mActivityManager = (android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (android.app.ActivityManager.RunningAppProcessInfo appProcess : mActivityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                processName = appProcess.processName;
                return processName.equals(context.getApplicationContext().getPackageName());
            }
        }
        return false;
    }


    public static Handler startHandlerThread(String threadName){
        HandlerThread thread  = new HandlerThread(threadName);
        thread.start();
        return new Handler(thread.getLooper());
    }

}
